# -*- coding: utf-8 -*-

import xmindparser
import random
import os
from time import sleep
from Common.public_method import utc_8
from src.Case.CaseData.add_case_data import AddCaseData
from Common.yaml_method import YamlMethod


class ImportCase:

    @staticmethod
    def insert_time():
        """
        生成13位随机数代替时间戳（生成用例速度太快，用时间戳的话会造成所有节点都是同一个时间戳）
        """
        return random.randint(1653041000000, 1653041999999)

    def topics_data(self, texts):
        """
        遍历xmind节点数据，并重新组合
        :param texts: 需要解析的节点数据
        :return:
        """
        children = []
        for topics in texts:
            dic = {'data': {}}
            dic['data']['created'] = self.insert_time()
            dic['data']['id'] = topics['id'].replace('-', '')[0:13]
            dic['data']['text'] = topics['title']
            if 'topics' in topics.keys():
                self.topics_data(topics['topics'])
                dic['children'] = self.topics_data(topics['topics'])
            else:
                dic['children'] = []
            children.append(dic)
        return children

    def new_case_data(self, case_name):
        """
        解析xmind文件后，组成新的用例数据
        :param case_name: 导入的用例名称
        :return:
        """
        # xmindparser配置
        xmindparser.config = {
            'showTopicId': True,  # 是否展示主题ID
            'hideEmptyValue': True,  # 是否隐藏空值
            'showStructure': False,  # 新增配置，是否展示结构值
            'showRelationship': True  # 新增配置，是否展示节点关系
        }

        # 打开文件路径
        evn = YamlMethod().read_data('environment.yaml')['evn']
        path = YamlMethod().read_data('path.yaml')['import_case'][evn]
        file_path = path + case_name
        file_name_list = os.listdir(path)
        for i in range(30):
            sleep(2)
            if case_name in file_name_list:
                # 解析成json数据类型
                content = xmindparser.xmind_to_dict(file_path)
                topic = content[0]['topic']
                text = topic['topics']
                root_id = topic['id'].replace('-', '')[0:13]
                root_text = topic['title']
                data = {'root': {'data': {'created': self.insert_time(), 'id': root_id, 'text': root_text}}}

                # 将测试用例数据添加到数据字典中
                case_data = self.topics_data(text)
                data['root']['children'] = case_data
                # 将xmind基础配置信息添加到数据字典中
                data['template'] = 'default'
                data['theme'] = 'fresh-green'
                data['version'] = '1.4.43'

                return data
        return 'No such file or directory'

    def import_case(self, file_name, case_name_id, create_user):
        """
        将导入的测试用例数据存入数据库
        :param file_name: 导入文件名称
        :param case_name_id：新生成的测试用例名称ID
        :param create_user：导入测试用例人
        :return:
        """
        code = YamlMethod().read_data('code.yaml')['code']
        text = self.new_case_data(file_name)
        if text != 'No such file or directory':
            case_time = utc_8()
            AddCaseData().add_case_data(str(text), case_name_id, case_time, case_time, create_user)

            res = {
                'code': code[0],
                'message': 'success',
                'data': {}
            }
            return res
        else:
            res = {
                'code': code[3],
                'message': text,
                'data': {}
            }
            return res
